package com.elitesland.system.repo;

import com.elitesland.core.base.BaseModel;
import com.elitesland.system.entity.QSysUserDO;
import com.elitesland.system.param.SysUserQueryParam;
import com.elitesland.system.service.SysRoleService;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;


/**
 * <pre>
 * [功能说明]
 * </pre>
 *
 * @author Mir
 * @date 2020/7/8
 */
@Component
@RequiredArgsConstructor
public class SysUserRepoProc {

    private final SysRoleService sysRoleService;

    public Predicate where(SysUserQueryParam param) {
        val sysUser = QSysUserDO.sysUserDO;

        Predicate predicate = sysUser.isNotNull().or(sysUser.isNull());

        predicate = StringUtils.isBlank(param.getKeyword()) ? predicate :
                ExpressionUtils.and(predicate, sysUser.username.like("%" + param.getKeyword() + "%")
                        .or(sysUser.firstName.like("%" + param.getKeyword() + "%"))
                        .or(sysUser.lastName.like("%" + param.getKeyword() + "%"))
                        .or(sysUser.mobile.like("%" + param.getKeyword() + "%"))
                        .or(sysUser.email.like("%" + param.getKeyword() + "%")));

        predicate = StringUtils.isBlank(param.getUsername()) ? predicate : ExpressionUtils.and(predicate, sysUser.username.like("%" + param.getUsername() + "%"));
        predicate = StringUtils.isBlank(param.getName()) ? predicate : ExpressionUtils.and(predicate, sysUser.firstName.like("%" + param.getName() + "%"));
        predicate = StringUtils.isBlank(param.getMobile()) ? predicate : ExpressionUtils.and(predicate, sysUser.mobile.like("%" + param.getMobile() + "%"));
        predicate = StringUtils.isBlank(param.getEmail()) ? predicate : ExpressionUtils.and(predicate, sysUser.email.like("%" + param.getEmail() + "%"));
        predicate = ObjectUtils.isEmpty(param.getEnabled()) ? predicate : ExpressionUtils.and(predicate, sysUser.enabled.eq(param.getEnabled()));

        predicate = ObjectUtils.isEmpty(param.getSourceType()) ? predicate : ExpressionUtils.and(predicate, sysUser.sourceType.eq(param.getSourceType()));

        if(CollectionUtils.isNotEmpty(param.getRoleIds())){
            val roles = sysRoleService.listByRoleIds(param.getRoleIds());
            val userIds = roles.stream().flatMap(r -> r.getUsers().stream().map(BaseModel::getId)).toArray(Long[]::new);

            predicate = ExpressionUtils.and(predicate, sysUser.id.in(userIds));
        }

        return predicate;
    }
}
